@namespace Oqtane.Modules.Admin.Site
@inherits ModuleBase
@using System.Text.RegularExpressions
@using Microsoft.Extensions.DependencyInjection
@inject NavigationManager NavigationManager
@inject ISiteService SiteService
@inject IPageService PageService
@inject ITenantService TenantService
@inject IDatabaseService DatabaseService
@inject IAliasService AliasService
@inject IThemeService  ThemeService
@inject ISettingService  SettingService
@inject ITimeZoneService TimeZoneService
@inject IServiceProvider ServiceProvider
@inject IStringLocalizer<Index> Localizer
@inject INotificationService NotificationService
@inject IStringLocalizer<SharedResources> SharedLocalizer
@inject IOutputCacheService CacheService

@if (_initialized)
{
    <form @ref="form" class="@(validated ? "was-validated" : "needs-validation")" novalidate>
        <div class="container">
            <div class="row mb-1 align-items-center">
                <Label Class="col-sm-3" For="name" HelpText="Enter the site name" ResourceKey="Name">Name: </Label>
                <div class="col-sm-9">
                    <input id="name" class="form-control" @bind="@_name" maxlength="200" required />
                </div>
            </div>
            <div class="row mb-1 align-items-center">
                <Label Class="col-sm-3" For="homepage" HelpText="Select the home page for the site (to be used if there is no page with a path of '/')" ResourceKey="HomePage">Home Page: </Label>
                <div class="col-sm-9">
                    <select id="homepage" class="form-select" @bind="@_homepageid" required>
                        <option value="-">&lt;@SharedLocalizer["Not Specified"]&gt;</option>
                        @foreach (Page page in _pages)
                        {
                            if (UserSecurity.ContainsRole(page.PermissionList, PermissionNames.View, RoleNames.Everyone))
                            {
                                <option value="@(page.PageId)">@(new string('-', page.Level * 2))@(page.Name)</option>
                            }
                        }
                    </select>
                </div>
            </div>
            <div class="row mb-1 align-items-center">
                <Label Class="col-sm-3" For="timezone" HelpText="Your time zone" ResourceKey="TimeZone">Time Zone:</Label>
                <div class="col-sm-9">
                    <select id="timezone" class="form-select" @bind="@_timezoneid">
                        <option value="">&lt;@SharedLocalizer["Not Specified"]&gt;</option>
                        @foreach (var timezone in _timezones)
                        {
                            <option value="@timezone.Id">@timezone.DisplayName</option>
                        }
                    </select>
                </div>
            </div>
            @if (UserSecurity.IsAuthorized(PageState.User, RoleNames.Host))
            {
                <div class="row mb-1 align-items-center">
                    <Label Class="col-sm-3" For="isDeleted" HelpText="Is this site deleted?" ResourceKey="IsDeleted">Deleted? </Label>
                    <div class="col-sm-9">
                        <select id="isDeleted" class="form-select" @bind="@_isdeleted" required>
                            <option value="True">@SharedLocalizer["Yes"]</option>
                            <option value="False">@SharedLocalizer["No"]</option>
                        </select>
                    </div>
                </div>
            }
            <div class="row mb-1 align-items-center">
                <Label Class="col-sm-3" For="sitemap" HelpText="The site map url for this site which can be submitted to search engines for indexing. The sitemap is cached for 5 minutes and the cache can be manually cleared." ResourceKey="SiteMap">Site Map: </Label>
                <div class="col-sm-9">
                    <div class="input-group">
                        <input id="sitemap" class="form-control" @bind="@_sitemap" disabled />
                        <a href="@_sitemap" class="btn btn-secondary" target="_new">@Localizer["Browse"]</a>
                        <button type="button" class="btn btn-danger" @onclick="EvictSitemapOutputCache">@Localizer["SiteMap.EvictCache"]</button>
                    </div>
                </div>
            </div>
            <div class="row mb-1 align-items-center">
                <Label Class="col-sm-3" For="siteguid" HelpText="The Unique Identifier For The Site" ResourceKey="SiteGuid">ID: </Label>
                <div class="col-sm-9">
                    <input id="siteguid" class="form-control" @bind="@_siteguid" required disabled />
                </div>
            </div>
            <div class="row mb-1 align-items-center">
                <Label Class="col-sm-3" For="version" HelpText="The site version (for site content migrations)" ResourceKey="Version">Version: </Label>
                <div class="col-sm-9">
                    <input id="version" class="form-control" @bind="@_version" required disabled />
                </div>
            </div>
        </div>
        <br />
        <Section Name="Theme" Heading="Theme" ResourceKey="Theme">
            <div class="container">
                <div class="row mb-1 align-items-center">
                    <Label Class="col-sm-3" For="defaultTheme" HelpText="Select the sites default theme" ResourceKey="DefaultTheme">Default Theme: </Label>
                    <div class="col-sm-9">
                        <select id="defaultTheme" class="form-select" value="@_themetype" @onchange="(e => ThemeChanged(e))" required>
                            @foreach (var theme in _themes)
                            {
                                <option value="@theme.TypeName">@theme.Name</option>
                            }
                        </select>
                    </div>
                </div>
                <div class="row mb-1 align-items-center">
                    <Label Class="col-sm-3" For="defaultContainer" HelpText="Select the default container for the site" ResourceKey="DefaultContainer">Default Container: </Label>
                    <div class="col-sm-9">
                        <select id="defaultContainer" class="form-select" @bind="@_containertype" required>
                            @if (_containers != null)
                            {
                                @foreach (var container in _containers)
                                {
                                    <option value="@container.TypeName">@container.Name</option>
                                }
                            }
                        </select>
                    </div>
                </div>
                <div class="row mb-1 align-items-center">
                    <Label Class="col-sm-3" For="defaultAdminContainer" HelpText="Select the default admin container for the site" ResourceKey="DefaultAdminContainer">Default Admin Container: </Label>
                    <div class="col-sm-9">
                        <select id="defaultAdminContainer" class="form-select" @bind="@_admincontainertype" required>
                            <option value="@Constants.DefaultAdminContainer">&lt;@Localizer["DefaultAdminContainer"]&gt;</option>
                            @if (_containers != null)
                            {
                                @foreach (var container in _containers)
                                {
                                    <option value="@container.TypeName">@container.Name</option>
                                }
                            }
                        </select>
                    </div>
                </div>
                <div class="row mb-1 align-items-center">
                    <Label Class="col-sm-3" For="cookieconsent" HelpText="Specify if cookie consent is enabled on this site. Please note this option must be used in conjunction with a Theme which supports cookie consent." ResourceKey="CookieConsent">Cookie Consent: </Label>
                    <div class="col-sm-9">
                        <select id="cookieconsent" class="form-select" @bind="@_cookieconsent">
                            <option value="">@SharedLocalizer["Disabled"]</option>
                            <option value="optin">@Localizer["OptIn"]</option>
                            <option value="optout">@Localizer["OptOut"]</option>
                        </select>
                    </div>
                </div>
            </div>
        </Section>
        <Section Name="Appearance" Heading="Appearance" ResourceKey="Appearance">
            <div class="container">
                <div class="row mb-1 align-items-center">
                    <Label Class="col-sm-3" For="logo" HelpText="Specify a logo for the site" ResourceKey="Logo">Logo: </Label>
                    <div class="col-sm-9">
                        <FileManager FileId="@_logofileid" Filter="@_imagefiles" @ref="_logofilemanager" />
                    </div>
                </div>
                <div class="row mb-1 align-items-center">
                    <Label Class="col-sm-3" For="favicon" HelpText="Specify a Favicon" ResourceKey="FavoriteIcon">Favicon: </Label>
                    <div class="col-sm-9">
                        <FileManager FileId="@_faviconfileid" Filter="ico,png,gif" @ref="_faviconfilemanager" />
                    </div>
                </div>
            </div>
        </Section>
        <Section Name="Functionality" Heading="Functionality" ResourceKey="Functionality">
            <div class="container">
                <div class="row mb-1 align-items-center">
                    <Label Class="col-sm-3" For="textEditor" HelpText="Select the text editor for the site" ResourceKey="TextEditor">Text Editor: </Label>
                    <div class="col-sm-9">
                        <select id="textEditor" class="form-select" @bind="@_textEditor" required>
                            @if (_textEditors != null)
                            {
                                @foreach (var textEditor in _textEditors)
                                {
                                    <option value="@textEditor.Value">@textEditor.Key</option>
                                }
                            }
                        </select>
                    </div>
                </div>
            </div>
        </Section>
        <Section Name="PageContent" Heading="Page Content" ResourceKey="PageContent">
            <div class="container">
                <div class="row mb-1 align-items-center">
                    <Label Class="col-sm-3" For="headcontent" HelpText="Optionally enter content to be included in the page head (ie. meta, link, or script tags)" ResourceKey="HeadContent">Head Content: </Label>
                    <div class="col-sm-9">
                        <textarea id="headcontent" class="form-control" @bind="@_headcontent" rows="3"></textarea>
                    </div>
                </div>
                <div class="row mb-1 align-items-center">
                    <Label Class="col-sm-3" For="bodycontent" HelpText="Optionally enter content to be included in the page body (ie. script tags)" ResourceKey="BodyContent">Body Content: </Label>
                    <div class="col-sm-9">
                        <textarea id="bodycontent" class="form-control" @bind="@_bodycontent" rows="3"></textarea>
                    </div>
                </div>
            </div>
        </Section>
        <Section Name="SMTP" Heading="SMTP Settings" ResourceKey="SMTPSettings">
            <div class="container">
                <div class="row mb-1 align-items-center">
                    <Label Class="col-sm-3" For="smtpenabled" HelpText="Specify if SMTP is enabled for this site" ResourceKey="SmtpEnabled">Enabled? </Label>
                    <div class="col-sm-9">
                        <select id="smtpenabled" class="form-select" value="@_smtpenabled" @onchange="(e => SMTPEnabledChanged(e))">
                            <option value="True">@SharedLocalizer["Yes"]</option>
                            <option value="False">@SharedLocalizer["No"]</option>
                        </select>
                    </div>
                </div>
                @if (_smtpenabled == "True" && UserSecurity.IsAuthorized(PageState.User, RoleNames.Host))
                {
                    <div class="row mb-1 align-items-center">
                        <div class="col-sm-3">
                        </div>
                        <div class="col-sm-9">
                            <strong>@Localizer["Smtp.Required.EnableNotificationJob"]</strong><br />
                        </div>
                    </div>
                    <div class="row mb-1 align-items-center">
                        <Label Class="col-sm-3" For="host" HelpText="Enter the host name of the SMTP server" ResourceKey="Host">Host: </Label>
                        <div class="col-sm-9">
                            <input id="host" class="form-control" @bind="@_smtphost" />
                        </div>
                    </div>
                    <div class="row mb-1 align-items-center">
                        <Label Class="col-sm-3" For="port" HelpText="Enter the port number for the SMTP server. Please note this field is required if you provide a host name." ResourceKey="Port">Port: </Label>
                        <div class="col-sm-9">
                            <input id="port" class="form-control" @bind="@_smtpport" />
                        </div>
                    </div>
                    <div class="row mb-1 align-items-center">
                        <Label Class="col-sm-3" For="smtpssl" HelpText="Specify the type of SSL connection for your SMTP server" ResourceKey="SmtpSSL">SSL Options: </Label>
                        <div class="col-sm-9">
                            <select id="smtpssl" class="form-select" @bind="@_smtpssl">
                                <option value="None">@Localizer["None"]</option>
                                <option value="Auto">@Localizer["Auto"]</option>
                                <option value="StartTls">@Localizer["StartTls"]</option>
                                <option value="SslOnConnect">@Localizer["SslOnConnect"]</option>
                                <option value="StartTlsWhenAvailable">@Localizer["StartTlsWhenAvailable"]</option>
                            </select>
                        </div>
                    </div>
                    <div class="row mb-1 align-items-center">
                        <Label Class="col-sm-3" For="smtpauthentication" HelpText="Specify the SMTP authentication type" ResourceKey="SMTPAuthentication">Authentication: </Label>
                        <div class="col-sm-9">
                            <select id="smtpauthentication" class="form-select" value="@_smtpauthentication" @onchange="(e => SMTPAuthenticationChanged(e))">
                                <option value="Basic">@Localizer["Basic"]</option>
                                <option value="OAuth2">@Localizer["OAuth2"]</option>
                            </select>
                        </div>
                    </div>
                    @if (_smtpauthentication == "Basic")
                    {
                        <div class="row mb-1 align-items-center">
                            <Label Class="col-sm-3" For="username" HelpText="Enter the username for your SMTP account" ResourceKey="SmtpUsername">Username: </Label>
                            <div class="col-sm-9">
                                <input id="username" class="form-control" @bind="@_smtpusername" autocomplete="off" />
                            </div>
                        </div>
                        <div class="row mb-1 align-items-center">
                            <Label Class="col-sm-3" For="password" HelpText="Enter the password for your SMTP account" ResourceKey="SmtpPassword">Password: </Label>
                            <div class="col-sm-9">
                                <div class="input-group">
                                    <input id="password" type="@_smtppasswordtype" class="form-control" @bind="@_smtppassword" autocomplete="off" />
                                    <button type="button" class="btn btn-secondary" @onclick="@ToggleSMTPPassword" tabindex="-1">@_togglesmtppassword</button>
                                </div>
                            </div>
                        </div>
                        <div class="row mb-1 align-items-center">
                            <Label Class="col-sm-3" For="relay" HelpText="Only specify this option if you have properly configured an SMTP Relay Service to route your outgoing mail. This option will send notifications from the user's email rather than from the Email Sender specified below." ResourceKey="SmtpRelay">Relay Configured? </Label>
                            <div class="col-sm-9">
                                <select id="relay" class="form-select" @bind="@_smtprelay" required>
                                    <option value="True">@SharedLocalizer["Yes"]</option>
                                    <option value="False">@SharedLocalizer["No"]</option>
                                </select>
                            </div>
                        </div>
                    }
                    else
                    {
                        <div class="row mb-1 align-items-center">
                            <Label Class="col-sm-3" For="smtpauthority" HelpText="The Authority Url for the SMTP provider" ResourceKey="SmtpAuthority">Authority Url:</Label>
                            <div class="col-sm-9">
                                <input id="smtpauthority" class="form-control" @bind="@_smtpauthority" />
                            </div>
                        </div>
                        <div class="row mb-1 align-items-center">
                            <Label Class="col-sm-3" For="smtpclientid" HelpText="The Client ID for the SMTP provider" ResourceKey="SmtpClientID">Client ID:</Label>
                            <div class="col-sm-9">
                                <input id="smtpclientid" class="form-control" @bind="@_smtpclientid" />
                            </div>
                        </div>
                        <div class="row mb-1 align-items-center">
                            <Label Class="col-sm-3" For="smtpclientsecret" HelpText="The Client Secret for the SMTP provider" ResourceKey="SmtpClientSecret">Client Secret:</Label>
                            <div class="col-sm-9">
                                <div class="input-group">
                                    <input type="@_smtpclientsecrettype" id="smtpclientsecret" class="form-control" @bind="@_smtpclientsecret" />
                                    <button type="button" class="btn btn-secondary" @onclick="@ToggleSmtpClientSecret">@_togglesmtpclientsecret</button>
                                </div>
                            </div>
                        </div>
                        <div class="row mb-1 align-items-center">
                            <Label Class="col-sm-3" For="smtpscopes" HelpText="A list of Scopes for the SMTP provider (separated by commas)" ResourceKey="SmtpScopes">Scopes:</Label>
                            <div class="col-sm-9">
                                <input id="smtpscopes" class="form-control" @bind="@_smtpscopes" />
                            </div>
                        </div>
                    }
                    <div class="row mb-1 align-items-center">
                        <Label Class="col-sm-3" For="sender" HelpText="Enter the email address which emails will be sent from. Please note that this email address usually needs to be authorized with the SMTP provider." ResourceKey="SmtpSender">Email Sender: </Label>
                        <div class="col-sm-9">
                            <input id="sender" class="form-control" @bind="@_smtpsender" />
                        </div>
                    </div>
                    <div class="row mb-1 align-items-center">
                        <Label Class="col-sm-3" For="retention" HelpText="Number of days of notifications to retain" ResourceKey="Retention">Retention (Days): </Label>
                        <div class="col-sm-9">
                            <input id="retention" class="form-control" type="number" min="0" step="1" @bind="@_retention" />
                        </div>
                    </div>
                    <button type="button" class="btn btn-secondary" @onclick="SendEmail">@Localizer["Smtp.TestConfig"]</button>
                    <br /><br />
                }
            </div>
        </Section>
        <Section Name="PWA" Heading="Progressive Web Application Settings" ResourceKey="PWASettings">
            <div class="container">
                <div class="row mb-1 align-items-center">
                    <Label Class="col-sm-3" For="isEnabled" HelpText="Select whether you would like this site to be available as a Progressive Web Application (PWA)" ResourceKey="EnablePWA">Is Enabled? </Label>
                    <div class="col-sm-9">
                        <select id="isEnabled" class="form-select" @bind="@_pwaisenabled" required>
                            <option value="True">@SharedLocalizer["Yes"]</option>
                            <option value="False">@SharedLocalizer["No"]</option>
                        </select>
                    </div>
                </div>
                <div class="row mb-1 align-items-center">
                    <Label Class="col-sm-3" For="appIcon" HelpText="Include an application icon for your PWA. It should be a PNG which is 192 X 192 pixels in dimension." ResourceKey="PwaApplicationIcon">App Icon: </Label>
                    <div class="col-sm-9">
                        <FileManager FileId="@_pwaappiconfileid" Filter="png" @ref="_pwaappiconfilemanager" />
                    </div>
                </div>
                <div class="row mb-1 align-items-center">
                    <Label Class="col-sm-3" For="splashIcon" HelpText="Include a splash icon for your PWA. It should be a PNG which is 512 X 512 pixels in dimension." ResourceKey="PwaSplashIcon">Splash Icon: </Label>
                    <div class="col-sm-9">
                        <FileManager FileId="@_pwasplashiconfileid" Filter="png" @ref="_pwasplashiconfilemanager" />
                    </div>
                </div>
            </div>
        </Section>
        @if (_aliases != null && UserSecurity.IsAuthorized(PageState.User, RoleNames.Host))
        {
            <Section Name="Aliases" Heading="Aliases" ResourceKey="Aliases">
                <div class="container">
                    <div class="row mb-1 align-items-center">
                        <Label Class="col-sm-3" For="aliases" HelpText="The urls for the site. This can include domain names (ie. domain.com), subdomains (ie. sub.domain.com) or virtual folders (ie. domain.com/folder)." ResourceKey="Aliases">Aliases: </Label>
                        <div class="col-sm-9">
                            <button type="button" class="btn btn-primary" @onclick="AddAlias">@SharedLocalizer["Add"]</button>
                            <Pager Items="@_aliases">
                                <Header>
                                    <th style="width: 1px;">&nbsp;</th>
                                    <th style="width: 1px;">&nbsp;</th>
                                    <th>@Localizer["AliasName"]</th>
                                    <th>@Localizer["AliasDefault"]</th>
                                </Header>
                                <Row>
                                    @if (context.AliasId != _aliasid)
                                    {
                                        <td>
                                            @if (_aliasid == -1)
                                            {
                                                <button type="button" class="btn btn-primary" @onclick="@(() => EditAlias(context))">@SharedLocalizer["Edit"]</button>
                                            }
                                        </td>
                                        <td>
                                            @if (_aliasid == -1)
                                            {
                                                <ActionDialog Action="Delete" OnClick="@(async () => await DeleteAlias(context))" ResourceKey="DeleteAlias" Class="btn btn-danger" Header="Delete Alias" Message="@string.Format(Localizer["Confirm.Alias.Delete", context.Name])" />
                                            }
                                        </td>
                                        <td>@context.Name</td>
                                        <td>@((context.IsDefault) ? SharedLocalizer["Yes"] : SharedLocalizer["No"])</td>
                                    }
                                    else
                                    {
                                        <td><button type="button" class="btn btn-success" @onclick="@(async () => await SaveAlias())">@SharedLocalizer["Save"]</button></td>
                                        <td><button type="button" class="btn btn-secondary" @onclick="@(async () => await CancelAlias())">@SharedLocalizer["Cancel"]</button></td>
                                        <td>
                                            <input id="aliasname" class="form-control" @bind="@_aliasname" />
                                        </td>
                                        <td>
                                            <select id="defaultalias" class="form-select" @bind="@_defaultalias" required>
                                                <option value="True">@SharedLocalizer["Yes"]</option>
                                                <option value="False">@SharedLocalizer["No"]</option>
                                            </select>
                                        </td>
                                    }
                                </Row>
                            </Pager>
                        </div>
                    </div>
                </div>
            </Section>
            <Section Name="Hosting" Heading="Hosting Model" ResourceKey="Hosting">
                <div class="container">
                    <div class="row mb-1 align-items-center">
                        <Label Class="col-sm-3" For="rendermode" HelpText="The default render mode for the site" ResourceKey="Rendermode">Render Mode: </Label>
                        <div class="col-sm-9">
                            <select id="rendermode" class="form-select" value="@_rendermode" @onchange="(e => RenderModeChanged(e))" required>
                                <option value="@RenderModes.Interactive">@(SharedLocalizer["RenderMode" + @RenderModes.Interactive])</option>
                                <option value="@RenderModes.Static">@(SharedLocalizer["RenderMode" + @RenderModes.Static])</option>
                                <option value="@RenderModes.Headless">@(SharedLocalizer["RenderMode" + @RenderModes.Headless])</option>
                            </select>
                        </div>
                    </div>
                    @if (_rendermode == RenderModes.Static)
                    {
                        <div class="row mb-1 align-items-center">
                            <Label Class="col-sm-3" For="enhancednavigation" HelpText="Indicates if enhanced navigation should be used with static rendering" ResourceKey="EnhancedNavigation">Enhanced Navigation: </Label>
                            <div class="col-sm-9">
                                <select id="enhancednavigation" class="form-select" @bind="@_enhancednavigation" required>
                                    <option value="True">@SharedLocalizer["Yes"]</option>
                                    <option value="False">@SharedLocalizer["No"]</option>
                                </select>
                            </div>
                        </div>
                    }
                    <div class="row mb-1 align-items-center">
                        <Label Class="col-sm-3" For="runtime" HelpText="The render mode for UI components which require interactivity" ResourceKey="Runtime">Interactivity: </Label>
                        <div class="col-sm-9">
                            <select id="runtime" class="form-select" @bind="@_runtime" required>
                                <option value="@Runtimes.Server">@(SharedLocalizer["Runtime" + @Runtimes.Server])</option>
                                <option value="@Runtimes.WebAssembly">@(SharedLocalizer["Runtime" + @Runtimes.WebAssembly])</option>
                                <option value="@Runtimes.Auto">@(SharedLocalizer["Runtime" + @Runtimes.Auto])</option>
                            </select>
                        </div>
                    </div>
                    <div class="row mb-1 align-items-center">
                        <Label Class="col-sm-3" For="prerender" HelpText="Specifies if interactive components should prerender their output on the server" ResourceKey="Prerender">Prerender: </Label>
                        <div class="col-sm-9">
                            <select id="prerender" class="form-select" @bind="@_prerender" required>
                                <option value="True">@SharedLocalizer["Yes"]</option>
                                <option value="False">@SharedLocalizer["No"]</option>
                            </select>
                        </div>
                    </div>
                    <div class="row mb-1 align-items-center">
                        <Label Class="col-sm-3" For="hybrid" HelpText="Specifies if the site can be integrated with an external .NET MAUI hybrid application" ResourceKey="Hybrid">Hybrid? </Label>
                        <div class="col-sm-9">
                            <select id="hybrid" class="form-select" @bind="@_hybrid" required>
                                <option value="True">@SharedLocalizer["Yes"]</option>
                                <option value="False">@SharedLocalizer["No"]</option>
                            </select>
                        </div>
                    </div>
                </div>
            </Section>
            <Section Name="TenantInformation" Heading="Database" ResourceKey="TenantInformation">
                <div class="container">
                    <div class="row mb-1 align-items-center">
                        <Label Class="col-sm-3" For="tenant" HelpText="The name of the database used for the site. Note that this is not the physical database name but rather the tenant name which is used within the framework to identify a database." ResourceKey="Tenant">Database: </Label>
                        <div class="col-sm-9">
                            <input id="tenant" class="form-control" @bind="@_tenant" readonly />
                        </div>
                    </div>
                    <div class="row mb-1 align-items-center">
                        <Label Class="col-sm-3" For="database" HelpText="The type of database" ResourceKey="Database">Type: </Label>
                        <div class="col-sm-9">
                            <input id="database" class="form-control" @bind="@_database" readonly />
                        </div>
                    </div>
                    <div class="row mb-1 align-items-center">
                        <Label Class="col-sm-3" For="connectionstring" HelpText="The name of the connection string in appsettings.json which will be used to connect to the database" ResourceKey="ConnectionString">Connection: </Label>
                        <div class="col-sm-9">
                            <input id="connectionstring" class="form-control" @bind="@_connectionstring" readonly />
                        </div>
                    </div>
                </div>
            </Section>
        }
        <br />
        <button type="button" class="btn btn-success" @onclick="SaveSite">@SharedLocalizer["Save"]</button>
        <ActionDialog Header="Delete Site" Message="@Localizer["Confirm.DeleteSite"]" Action="Delete" Security="SecurityAccessLevel.Host" Class="btn btn-danger" OnClick="@(async () => await DeleteSite())" ResourceKey="DeleteSite" />
        <br />
        <br />
        <AuditInfo CreatedBy="@_createdby" CreatedOn="@_createdon" ModifiedBy="@_modifiedby" ModifiedOn="@_modifiedon" DeletedBy="@_deletedby" DeletedOn="@_deletedon"></AuditInfo>
    </form>
}

@code {
    private ElementReference form;
    private bool validated = false;
    private bool _initialized = false;
    private List<ThemeControl> _themes = new List<ThemeControl>();
    private List<ThemeControl> _containers = new List<ThemeControl>();
    private List<Page> _pages;
    private List<Models.TimeZone> _timezones;

    private string _name = string.Empty;
    private string _homepageid = "-";
    private string _timezoneid = string.Empty;
    private string _isdeleted;
    private string _sitemap = "";
    private string _siteguid = "";
    private string _version = "";

    private int _logofileid = -1;
    private FileManager _logofilemanager;
    private int _faviconfileid = -1;
    private FileManager _faviconfilemanager;
    private string _themetype = "";
    private string _containertype = "";
    private string _admincontainertype = "";
    private string _cookieconsent = "";

    private Dictionary<string, string> _textEditors = new Dictionary<string, string>();
    private string _textEditor = "";
    private string _imagefiles = string.Empty;

    private string _headcontent = string.Empty;
    private string _bodycontent = string.Empty;

    private string _smtpenabled = "False";
    private string _smtpauthentication = "Basic";
    private string _smtphost = string.Empty;
    private string _smtpport = string.Empty;
    private string _smtpssl = "Auto";
    private string _smtpusername = string.Empty;
    private string _smtppassword = string.Empty;
    private string _smtppasswordtype = "password";
    private string _togglesmtppassword = string.Empty;
    private string _smtpauthority = string.Empty;
    private string _smtpclientid = string.Empty;
    private string _smtpclientsecret = string.Empty;
    private string _smtpclientsecrettype = "password";
    private string _togglesmtpclientsecret = string.Empty;
    private string _smtpscopes = string.Empty;
    private string _smtpsender = string.Empty;
    private string _smtprelay = "False";
    private int _retention = 30;

    private string _pwaisenabled;
    private int _pwaappiconfileid = -1;
    private FileManager _pwaappiconfilemanager;
    private int _pwasplashiconfileid = -1;
    private FileManager _pwasplashiconfilemanager;

    private List<Alias> _aliases;
    private int _aliasid = -1;
    private string _aliasname;
    private string _defaultalias;

    private string _rendermode = RenderModes.Interactive;
    private string _enhancednavigation = "True";
    private string _runtime = Runtimes.Server;
    private string _prerender = "True";
    private string _hybrid = "False";

    private string _tenant = string.Empty;
    private string _database = string.Empty;
    private string _connectionstring = string.Empty;

    private string _createdby;
    private DateTime _createdon;
    private string _modifiedby;
    private DateTime _modifiedon;
    private string _deletedby;
    private DateTime? _deletedon;

    public override SecurityAccessLevel SecurityAccessLevel => SecurityAccessLevel.Admin;

    protected override async Task OnInitializedAsync()
    {
        try
        {
            if (PageState.QueryString.ContainsKey("updated"))
            {
                AddModuleMessage(Localizer["Success.Settings.SaveSite"], MessageType.Success);
            }

            Site site = await SiteService.GetSiteAsync(PageState.Site.SiteId);
            if (site != null)
            {
                _timezones = TimeZoneService.GetTimeZones();
                var settings = await SettingService.GetSiteSettingsAsync(site.SiteId);

                _pages = await PageService.GetPagesAsync(PageState.Site.SiteId);

                _name = site.Name;
                _timezoneid = site.TimeZoneId;
                if (site.HomePageId != null)
                {
                    _homepageid = site.HomePageId.Value.ToString();
                }
                _isdeleted = site.IsDeleted.ToString();
                _sitemap = PageState.Alias.Protocol + PageState.Alias.Name + "/sitemap.xml";
                _siteguid = site.SiteGuid;
                _version = site.Version;

                // appearance
                if (site.LogoFileId != null)
                {
                    _logofileid = site.LogoFileId.Value;
                }

                if (site.FaviconFileId != null)
                {
                    _faviconfileid = site.FaviconFileId.Value;
                }
                var themes = new List<Theme>();
                foreach (var theme in PageState.Site.Themes)
                {
                    if (UserSecurity.IsAuthorized(PageState.User, PermissionNames.Utilize, theme.PermissionList))
                    {
                        themes.Add(theme);
                    }
                }
                _themes = ThemeService.GetThemeControls(themes);
                _themetype = (!string.IsNullOrEmpty(site.DefaultThemeType)) ? site.DefaultThemeType : Constants.DefaultTheme;
                _containers = ThemeService.GetContainerControls(themes, _themetype);
                _containertype = (!string.IsNullOrEmpty(site.DefaultContainerType)) ? site.DefaultContainerType : Constants.DefaultContainer;
                _admincontainertype = (!string.IsNullOrEmpty(site.AdminContainerType)) ? site.AdminContainerType : Constants.DefaultAdminContainer;
                _cookieconsent = SettingService.GetSetting(settings, "CookieConsent", string.Empty);

                // functionality
                var textEditors = ServiceProvider.GetServices<ITextEditor>();
                foreach (var textEditor in textEditors)
                {
                    _textEditors.Add(textEditor.Name, Utilities.GetFullTypeName(textEditor.GetType().AssemblyQualifiedName));
                }
                _textEditor = SettingService.GetSetting(settings, "TextEditor", Constants.DefaultTextEditor);
                _imagefiles = SettingService.GetSetting(settings, "ImageFiles", Constants.ImageFiles);
                _imagefiles = (string.IsNullOrEmpty(_imagefiles)) ? Constants.ImageFiles : _imagefiles;

                // page content
                _headcontent = site.HeadContent;
                _bodycontent = site.BodyContent;

                // SMTP
                _smtpenabled = SettingService.GetSetting(settings, "SMTPEnabled", "False");
                if (UserSecurity.IsAuthorized(PageState.User, RoleNames.Host))
                {
                    _smtphost = SettingService.GetSetting(settings, "SMTPHost", string.Empty);
                    _smtpport = SettingService.GetSetting(settings, "SMTPPort", string.Empty);
                    _smtpssl = SettingService.GetSetting(settings, "SMTPSSL", "Auto");
                    if (_smtpssl == "True") _smtpssl = "SslOnConnect";
                    if (_smtpssl == "False") _smtpssl = "StartTlsWhenAvailable";
                    _smtpauthentication = SettingService.GetSetting(settings, "SMTPAuthentication", "Basic");
                    _smtpusername = SettingService.GetSetting(settings, "SMTPUsername", string.Empty);
                    _smtppassword = SettingService.GetSetting(settings, "SMTPPassword", string.Empty);
                    _togglesmtppassword = SharedLocalizer["ShowPassword"];
                    _smtpauthority = SettingService.GetSetting(settings, "SMTPAuthority", string.Empty);
                    _smtpclientid = SettingService.GetSetting(settings, "SMTPClientId", string.Empty);
                    _smtpclientsecret = SettingService.GetSetting(settings, "SMTPClientSecret", string.Empty);
                    _togglesmtpclientsecret = SharedLocalizer["ShowPassword"];
                    _smtpscopes = SettingService.GetSetting(settings, "SMTPScopes", string.Empty);
                    _smtpsender = SettingService.GetSetting(settings, "SMTPSender", string.Empty);
                    _smtprelay = SettingService.GetSetting(settings, "SMTPRelay", "False");
                    _retention = int.Parse(SettingService.GetSetting(settings, "NotificationRetention", "30"));
                }

                // PWA
                _pwaisenabled = site.PwaIsEnabled.ToString();
                if (site.PwaAppIconFileId != null)
                {
                    _pwaappiconfileid = site.PwaAppIconFileId.Value;
                }
                if (site.PwaSplashIconFileId != null)
                {
                    _pwasplashiconfileid = site.PwaSplashIconFileId.Value;
                }

                // aliases
                await GetAliases();

                // hosting model
                _rendermode = site.RenderMode;
                _enhancednavigation = site.EnhancedNavigation.ToString();
                _runtime = site.Runtime;
                _prerender = site.Prerender.ToString();
                _hybrid = site.Hybrid.ToString();

                // database
                if (UserSecurity.IsAuthorized(PageState.User, RoleNames.Host))
                {
                    var tenants = await TenantService.GetTenantsAsync();
                    var _databases = await DatabaseService.GetDatabasesAsync();
                    var tenant = tenants.Find(item => item.TenantId == PageState.Alias.TenantId);
                    if (tenant != null)
                    {
                        _tenant = tenant.Name;
                        // hack - there are 3 providers with SqlServerDatabase DBTypes - so we are choosing the last one in alphabetical order
                        _database = _databases.Where(item => item.DBType == tenant.DBType).OrderBy(item => item.Name).Last()?.Name;
                        _connectionstring = tenant.DBConnectionString;
                    }
                }

                // audit
                _createdby = site.CreatedBy;
                _createdon = site.CreatedOn;
                _modifiedby = site.ModifiedBy;
                _modifiedon = site.ModifiedOn;
                _deletedby = site.DeletedBy;
                _deletedon = site.DeletedOn;

                _initialized = true;
            }
        }
        catch (Exception ex)
        {
            await logger.LogError(ex, "Error Loading Site {SiteId} {Error}", PageState.Site.SiteId, ex.Message);
            AddModuleMessage(ex.Message, MessageType.Error);
        }
    }

    private async void ThemeChanged(ChangeEventArgs e)
    {
        try
        {
            _themetype = (string)e.Value;
            _containers = ThemeService.GetContainerControls(PageState.Site.Themes, _themetype);
            _containertype = _containers.First().TypeName;
            _admincontainertype = Constants.DefaultAdminContainer;
            StateHasChanged();
        }
        catch (Exception ex)
        {
            await logger.LogError(ex, "Error Loading Containers For Theme {ThemeType} {Error}", _themetype, ex.Message);
            AddModuleMessage(Localizer["Error.Theme.LoadPane"], MessageType.Error);
        }
    }

    private void RenderModeChanged(ChangeEventArgs e)
    {
        _rendermode = (string)e.Value;
        switch (_rendermode)
        {
            case RenderModes.Interactive:
                _prerender = "True";
                break;
            case RenderModes.Static:
                _prerender = "False";
                break;
            case RenderModes.Headless:
                _prerender = "False";
                break;
        }
    }

    private async Task SaveSite()
    {
        validated = true;
        var interop = new Interop(JSRuntime);
        if (await interop.FormValid(form))
        {
            try
            {
                if (_name != string.Empty && _themetype != "-" && _containertype != "-")
                {
                    var site = await SiteService.GetSiteAsync(PageState.Site.SiteId);
                    if (site != null)
                    {
                        site.Name = _name;
                        site.TimeZoneId = _timezoneid;
                        site.HomePageId = (_homepageid != "-" ? int.Parse(_homepageid) : null);
                        site.IsDeleted = (_isdeleted == null ? true : Boolean.Parse(_isdeleted));

                        // appearance
                        site.LogoFileId = null;
                        var logofileid = _logofilemanager.GetFileId();
                        if (logofileid != -1)
                        {
                            site.LogoFileId = logofileid;
                            if (logofileid != _logofileid)
                            {
                                _logofileid = logofileid;
                            }
                        }
                        int? faviconFieldId = _faviconfilemanager.GetFileId();
                        if (faviconFieldId == -1) faviconFieldId = null;
                        if (site.FaviconFileId != faviconFieldId)
                        {
                            site.FaviconFileId = faviconFieldId;
                        }
                        if (site.DefaultThemeType != _themetype)
                        {
                            site.DefaultThemeType = _themetype;
                        }
                        if (site.DefaultContainerType != _containertype)
                        {
                            site.DefaultContainerType = _containertype;
                        }
                        site.AdminContainerType = _admincontainertype;

                        // page content
                        if (site.HeadContent != _headcontent)
                        {
                            site.HeadContent = _headcontent;
                        }
                        if (site.BodyContent != _bodycontent)
                        {
                            site.BodyContent = _bodycontent;
                        }

                        // PWA
                        if (site.PwaIsEnabled.ToString() != _pwaisenabled)
                        {
                            site.PwaIsEnabled = Boolean.Parse(_pwaisenabled);
                        }
                        int? pwaappiconfileid = _pwaappiconfilemanager.GetFileId();
                        if (pwaappiconfileid == -1) pwaappiconfileid = null;
                        if (site.PwaAppIconFileId != pwaappiconfileid)
                        {
                            site.PwaAppIconFileId = pwaappiconfileid;
                        }
                        int? pwasplashiconfileid = _pwasplashiconfilemanager.GetFileId();
                        if (pwasplashiconfileid == -1) pwasplashiconfileid = null;
                        if (site.PwaSplashIconFileId != pwasplashiconfileid)
                        {
                            site.PwaSplashIconFileId = pwasplashiconfileid;
                        }

                        // hosting model
                        if (UserSecurity.IsAuthorized(PageState.User, RoleNames.Host))
                        {
                            site.RenderMode = _rendermode;
                            site.EnhancedNavigation = bool.Parse(_enhancednavigation);
                            site.Runtime = _runtime;
                            site.Prerender = bool.Parse(_prerender);
                            site.Hybrid = bool.Parse(_hybrid);
                        }

                        site = await SiteService.UpdateSiteAsync(site);

                        // SMTP
                        var settings = await SettingService.GetSiteSettingsAsync(site.SiteId);
                        settings = SettingService.SetSetting(settings, "SMTPEnabled", _smtpenabled, true);
                        if (UserSecurity.IsAuthorized(PageState.User, RoleNames.Host))
                        {
                            settings = SettingService.SetSetting(settings, "SMTPHost", _smtphost, true);
                            settings = SettingService.SetSetting(settings, "SMTPPort", _smtpport, true);
                            settings = SettingService.SetSetting(settings, "SMTPSSL", _smtpssl, true);
                            settings = SettingService.SetSetting(settings, "SMTPAuthentication", _smtpauthentication, true);
                            settings = SettingService.SetSetting(settings, "SMTPUsername", _smtpusername, true);
                            settings = SettingService.SetSetting(settings, "SMTPPassword", _smtppassword, true);
                            settings = SettingService.SetSetting(settings, "SMTPAuthority", _smtpauthority, true);
                            settings = SettingService.SetSetting(settings, "SMTPClientId", _smtpclientid, true);
                            settings = SettingService.SetSetting(settings, "SMTPClientSecret", _smtpclientsecret, true);
                            settings = SettingService.SetSetting(settings, "SMTPScopes", _smtpscopes, true);
                            settings = SettingService.SetSetting(settings, "SMTPSender", _smtpsender, true);
                            settings = SettingService.SetSetting(settings, "SMTPRelay", _smtprelay, true);
                            settings = SettingService.SetSetting(settings, "NotificationRetention", _retention.ToString(), true);
                        }

                        //cookie consent
                        settings = SettingService.SetSetting(settings, "CookieConsent", _cookieconsent);

                        // functionality
                        settings = SettingService.SetSetting(settings, "TextEditor", _textEditor);

                        settings = SettingService.SetSetting(settings, "SiteGuid", _siteguid, true);
                        await SettingService.UpdateSiteSettingsAsync(settings, site.SiteId);

                        await logger.LogInformation("Site Settings Saved {Site}", site);

                        NavigationManager.NavigateTo(NavigateUrl(PageState.Page.Path, "updated=true"), true); // reload
                    }
                }
                else
                {
                    AddModuleMessage(Localizer["Message.Required.SiteName"], MessageType.Warning);
                }
            }
            catch (Exception ex)
            {
                await logger.LogError(ex, "Error Saving Site {SiteId} {Error}", PageState.Site.SiteId, ex.Message);
                AddModuleMessage(Localizer["Error.SaveSite"], MessageType.Error);
            }
        }
        else
        {
            AddModuleMessage(SharedLocalizer["Message.InfoRequired"], MessageType.Warning);
        }
    }

    private async Task DeleteSite()
    {
        try
        {
            var aliases = await AliasService.GetAliasesAsync();
            if (aliases.Any(item => item.SiteId != PageState.Site.SiteId || item.TenantId != PageState.Alias.TenantId))
            {
                await SiteService.DeleteSiteAsync(PageState.Site.SiteId);
                await logger.LogInformation("Site Deleted {SiteId}", PageState.Site.SiteId);

                foreach (Alias alias in aliases.Where(item => item.SiteId == PageState.Site.SiteId && item.TenantId == PageState.Alias.TenantId))
                {
                    await AliasService.DeleteAliasAsync(alias.AliasId);
                }

                var redirect = aliases.First(item => item.SiteId != PageState.Site.SiteId || item.TenantId != PageState.Alias.TenantId);
                NavigationManager.NavigateTo(PageState.Uri.Scheme + "://" + redirect.Name, true);
            }
            else
            {
                AddModuleMessage(Localizer["Message.FailAuth.DeleteSite"], MessageType.Warning);
            }
        }
        catch (Exception ex)
        {
            await logger.LogError(ex, "Error Deleting Site {SiteId} {Error}", PageState.Site.SiteId, ex.Message);
            AddModuleMessage(Localizer["Error.DeleteSite"], MessageType.Error);
        }
    }

    private void SMTPAuthenticationChanged(ChangeEventArgs e)
    {
        _smtpauthentication = (string)e.Value;
        StateHasChanged();
    }

    private void SMTPEnabledChanged(ChangeEventArgs e)
    {
        _smtpenabled = (string)e.Value;
        StateHasChanged();
    }

    private void ToggleSMTPPassword()
    {
        if (_smtppasswordtype == "password")
        {
            _smtppasswordtype = "text";
            _togglesmtppassword = SharedLocalizer["HidePassword"];
        }
        else
        {
            _smtppasswordtype = "password";
            _togglesmtppassword = SharedLocalizer["ShowPassword"];
        }
    }

    private void ToggleSmtpClientSecret()
    {
        if (_smtpclientsecrettype == "password")
        {
            _smtpclientsecrettype = "text";
            _togglesmtpclientsecret = SharedLocalizer["HidePassword"];
        }
        else
        {
            _smtpclientsecrettype = "password";
            _togglesmtpclientsecret = SharedLocalizer["ShowPassword"];
        }
    }

    private async Task SendEmail()
    {
        if (_smtphost != "" && _smtpport != "" && _smtpsender != "")
        {
            try
            {
                var settings = await SettingService.GetSiteSettingsAsync(PageState.Site.SiteId);
                settings = SettingService.SetSetting(settings, "SMTPHost", _smtphost, true);
                settings = SettingService.SetSetting(settings, "SMTPPort", _smtpport, true);
                settings = SettingService.SetSetting(settings, "SMTPSSL", _smtpssl, true);
                settings = SettingService.SetSetting(settings, "SMTPAuthentication", _smtpauthentication, true);
                settings = SettingService.SetSetting(settings, "SMTPUsername", _smtpusername, true);
                settings = SettingService.SetSetting(settings, "SMTPPassword", _smtppassword, true);
                settings = SettingService.SetSetting(settings, "SMTPAuthority", _smtpauthority, true);
                settings = SettingService.SetSetting(settings, "SMTPClientId", _smtpclientid, true);
                settings = SettingService.SetSetting(settings, "SMTPClientSecret", _smtpclientsecret, true);
                settings = SettingService.SetSetting(settings, "SMTPScopes", _smtpscopes, true);
                settings = SettingService.SetSetting(settings, "SMTPSender", _smtpsender, true);
                await SettingService.UpdateSiteSettingsAsync(settings, PageState.Site.SiteId);
                await logger.LogInformation("Site SMTP Settings Saved");

                await NotificationService.AddNotificationAsync(new Notification(PageState.Site.SiteId, PageState.User, PageState.Site.Name + " SMTP Configuration Test", "SMTP Server Is Configured Correctly."));
                AddModuleMessage(Localizer["Info.Smtp.SaveSettings"], MessageType.Info);
                await ScrollToPageTop();
            }
            catch (Exception ex)
            {
                await logger.LogError(ex, "Error Testing SMTP Configuration");
                AddModuleMessage(Localizer["Error.Smtp.TestConfig"], MessageType.Error);
            }
        }
        else
        {
            AddModuleMessage(Localizer["Message.Required.Smtp"], MessageType.Warning);
        }
    }

    private async Task GetAliases()
    {
        if (UserSecurity.IsAuthorized(PageState.User, RoleNames.Host))
        {
            _aliases = await AliasService.GetAliasesAsync();
            _aliases = _aliases.Where(item => item.SiteId == PageState.Site.SiteId && item.TenantId == PageState.Alias.TenantId).OrderBy(item => item.AliasId).ToList();
        }
    }

    private void AddAlias()
    {
        _aliases.Add(new Alias { AliasId = 0, Name = "", IsDefault = false });
        _aliasid = 0;
        _aliasname = "";
        _defaultalias = "False";
        StateHasChanged();
    }

    private void EditAlias(Alias alias)
    {
        _aliasid = alias.AliasId;
        _aliasname = alias.Name;
        _defaultalias = alias.IsDefault.ToString();
        StateHasChanged();
    }

    private async Task DeleteAlias(Alias alias)
    {
        if (UserSecurity.IsAuthorized(PageState.User, RoleNames.Host))
        {
            await AliasService.DeleteAliasAsync(alias.AliasId);
            await GetAliases();
            StateHasChanged();
        }
    }

    private async Task SaveAlias()
    {
        if (UserSecurity.IsAuthorized(PageState.User, RoleNames.Host))
        {
            if (!string.IsNullOrEmpty(_aliasname))
            {
                var aliases = await AliasService.GetAliasesAsync();

                int protocolIndex = _aliasname.IndexOf("://", StringComparison.OrdinalIgnoreCase);
                if (protocolIndex != -1)
                {
                    _aliasname = _aliasname.Substring(protocolIndex + 3);
                }

                var alias = aliases.FirstOrDefault(item => item.Name == _aliasname);

                bool unique = (alias == null || alias.AliasId == _aliasid);

                if (unique)
                {
                    if (_aliasid == 0)
                    {
                        alias = new Alias { SiteId = PageState.Site.SiteId, TenantId = PageState.Alias.TenantId, Name = _aliasname, IsDefault = bool.Parse(_defaultalias) };
                        await AliasService.AddAliasAsync(alias);
                    }
                    else
                    {
                        alias = _aliases.SingleOrDefault(item => item.AliasId == _aliasid);
                        if (alias != null)
                        {
                            alias.Name = _aliasname;
                            alias.IsDefault = bool.Parse(_defaultalias);
                            await AliasService.UpdateAliasAsync(alias);
                        }
                    }

                    await GetAliases();
                    _aliasid = -1;
                    _aliasname = "";
                    StateHasChanged();
                }
                else // Duplicate alias
                {
                    AddModuleMessage(Localizer["Message.Aliases.Taken"], MessageType.Warning);
                    await ScrollToPageTop();
                }
            }
        }
    }

    private async Task CancelAlias()
    {
        await GetAliases();
        _aliasid = -1;
        _aliasname = "";
        StateHasChanged();
    }

    private async Task EvictSitemapOutputCache() {
        await CacheService.EvictByTag(Constants.SitemapOutputCacheTag);
        AddModuleMessage(Localizer["Success.SiteMap.CacheEvicted"], MessageType.Success);
    }
}
